package com.cy.pj.sys.service.impl;

import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.pojo.CheckBox;
import com.cy.pj.sys.dao.SysRoleDao;
import com.cy.pj.sys.dao.SysRoleMenuDao;
import com.cy.pj.sys.pojo.SysRole;
import com.cy.pj.sys.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional(readOnly = false,rollbackFor = Throwable.class,isolation = Isolation.READ_COMMITTED)
@Service
public class SysRoleServiceImpl implements SysRoleService {
    @Autowired
    private SysRoleDao sysRoleDao;

    @Autowired
    private SysRoleMenuDao sysRoleMenuDao;

    public List<CheckBox> findCheckRoles(){
        //....
        return sysRoleDao.selectCheckRoles();
    }

    public SysRole findById(Integer id){
        SysRole roleMenu=sysRoleDao.selectById(id);//id,name,note
        if(roleMenu==null)
            throw new ServiceException("记录可能已经不存在");
        return roleMenu;
    }

    @Transactional
    @Override
    public int updateRole(SysRole sysRole) {
        //1.更新角色自身信息
        //2.保存角色自身信息
        int rows=sysRoleDao.updateRole(sysRole);
        if(rows==0)
            throw new ServiceException("记录可能已经不存在");
        //3.更新角色和菜单关系数据
        //3.1删除原有关系
        sysRoleMenuDao.deleteByRoleId(sysRole.getId());
        //System.out.println("menuIds="+Arrays.toString(menuIds));
        //3.2添加新的关系
        sysRoleMenuDao.insertRoleMenus(sysRole.getId(),sysRole.getMenuIds());
        return rows;
    }

    @Transactional
    @Override
    public int saveRole(SysRole sysRole) {
        //1.参数校验(自己校验)
        //2.保存角色自身信息
        int rows=sysRoleDao.insertRole(sysRole);
        //3.保存角色和菜单关系数据
        sysRoleMenuDao.insertRoleMenus(sysRole.getId(),sysRole.getMenuIds());
        return rows;
    }

    @Transactional(readOnly = true)
    @Override
    public List<SysRole> findRoles(SysRole sysRole) {
        return sysRoleDao.selectRoles(sysRole);
    }
}
